package cn.brilliantfuture.commentry.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.apache.log4j.Logger;

import com.cloopen.rest.sdk.CCPRestSmsSDK;

public class SMSScheduler extends Thread {
	private static Logger logger = Logger.getLogger(SMSScheduler.class);
	
	/**
	 * 彩信猫信息通道
	 */
	public static final int MMS_CAT_CHANNEL = 1;
	
	/**
	 * 台湾YOYO8信息通道
	 */
	public static final int TAIWAN_YOYO_CHANNEL = 2;
	
	/**
	 * 云通讯信息通道
	 */
	public static final int YUNTONGXUN_CHANNEL = 3;
	
	private static Map<String, String> ytxmap = null;
	static{
		ytxmap = new HashMap<String, String>();
		ytxmap.put("121", "32788");
		ytxmap.put("111", "32787");
		ytxmap.put("174", "32785");
	}
	
	private String phones;
	private Integer smsChannel;
	private String content;
	private Object[] objs;
	private String key;
	private String postfix;
	private boolean isDelay;
	
	public SMSScheduler(String phones, String content, Object[] objs, String key, Integer smsChannel, String postfix, boolean isDelay) {
		this.phones = phones;
		this.content = content;
		this.objs = objs;
		this.key = key;
		this.smsChannel = smsChannel;
		this.postfix = postfix;
		this.isDelay = isDelay;
	}

	@Override
	public void run() {
		logger.info("Start asyn execute send message");
		StringBuffer sb = new StringBuffer();

		if (MMS_CAT_CHANNEL == smsChannel.intValue()){
			content += "【" + postfix + "】";
		}
		
		String message = content;
		
		if (isDelay){
			if (!validSMSDelayInfo(phones, message, smsChannel)){
				try {
					content = URLEncoder.encode(content, "utf8");
				} catch (UnsupportedEncodingException e) {
					logger.error(e.getMessage());
				}
				
				String returnValue = null;
				
				if (MMS_CAT_CHANNEL == smsChannel.intValue() || TAIWAN_YOYO_CHANNEL == smsChannel.intValue()) {
					if (MMS_CAT_CHANNEL == smsChannel.intValue()){
						sb.append("http://sms.acsm.cn/smsservice-web/SMSMessageServiceChannel?username=acsm&passwd=acsm@197&phones=");
						sb.append(phones);
						sb.append("&content=");
						sb.append(content);
					} else if (TAIWAN_YOYO_CHANNEL == smsChannel.intValue()){
						Random random = new Random();
						int prodId = random.nextInt(100000000);
						int msgId = random.nextInt(100000000);
						sb.append("http://www.yoyo8.com.tw/SMSBridge.php?");
						sb.append("MemberID=baokulife");
						sb.append("&Password=").append(MD5.getMD5("baokulife:baokulife1:" + prodId + ":" + msgId));
						sb.append("&MobileNo=").append(phones);
						sb.append("&CharSet=U");
						sb.append("&SMSMessage=").append(content);
						sb.append("&SourceProdID=").append(prodId);
						sb.append("&SourceMsgID=").append(msgId);
					}
					
					returnValue = HttpUtil.getInvoke(sb.toString());
					returnValue = returnValue.replace("\r\n", "");
					logger.info("Return value : " + returnValue);
				} else if (YUNTONGXUN_CHANNEL == smsChannel.intValue()) {
					HashMap<String, Object> result = null;
					CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
					restAPI.init("sandboxapp.cloopen.com", "8883");
					restAPI.setAccount("8a48b5514e5298b9014e704f41781c4d", "6657a44a44b54114984a64196d69d434");
					restAPI.setAppId("aaf98f894e52805a014e704f90f919f2");
					
					if (ytxmap.containsKey(key)) {
						
						String[] datas = new String[objs.length];
						
						for (int i = 0; i < objs.length; i++) {
							message += objs[i];
							datas[i] = objs[i].toString();
							if (i < objs.length - 1) {
								message += "|";
							}
						}
						
						result = restAPI.sendTemplateSMS(phones, ytxmap.get(key) , datas);

						logger.info("SDKTestGetSubAccounts result -> " + result);
				
						if("000000".equals(result.get("statusCode"))){
							@SuppressWarnings("unchecked")
							HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
							Set<String> keySet = data.keySet();
							for(String key:keySet){
								Object object = data.get(key);
								logger.info(key +" = "+object);
							}
							returnValue = "1";
						}else{
							logger.info("错误码 = " + result.get("statusCode") +" 错误信息 = "+result.get("statusMsg"));
							returnValue = "-1";
						}
					} else {
						returnValue = null;
					}
				}

				if (null != returnValue) {
					Connection conn = null;
					PreparedStatement pstm = null;
					
					try {
						conn = JDBCDataSource.getConnection();
						
						conn.setAutoCommit(false);
						
						pstm = conn.prepareStatement("insert into send_record(phone, content, sms_channel, status, is_send, insert_time) values (?, ?, ?, ?, ?, now())");
						pstm.setString(1, phones);
						pstm.setString(2, message);
						pstm.setInt(3, smsChannel);
						
						if ("1".equals(returnValue)) {
							pstm.setInt(4, 7);
							pstm.setBoolean(5, true);
						}else {
							pstm.setInt(4, 8);
							pstm.setBoolean(5, false);
						}
						
						pstm.executeUpdate();
						
						conn.commit();
						conn.setAutoCommit(true);
					} catch (Exception e) {
						try {
							conn.rollback();
						} catch (SQLException e1) {
							logger.error("Rollback fail\n" + e1.getMessage());
						}
						logger.error("Save sms send record fail\n" + e.getMessage());
					} finally {
						try {
							if (pstm != null)
								pstm.close();
							if (conn != null)
								conn.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
				}
				
			}
		} else {
			try {
				content = URLEncoder.encode(content, "utf8");
			} catch (UnsupportedEncodingException e) {
				logger.error(e.getMessage());
			}

			String returnValue = null;
			
			if (MMS_CAT_CHANNEL == smsChannel.intValue() || TAIWAN_YOYO_CHANNEL == smsChannel.intValue()) {
				if (MMS_CAT_CHANNEL == smsChannel.intValue()){
					sb.append("http://sms.acsm.cn/smsservice-web/SMSMessageServiceChannel?username=acsm&passwd=acsm@197&phones=");
					sb.append(phones);
					sb.append("&content=");
					sb.append(content);
				} else if (TAIWAN_YOYO_CHANNEL == smsChannel.intValue()){
					Random random = new Random();
					int prodId = random.nextInt(100000000);
					int msgId = random.nextInt(100000000);
					sb.append("http://www.yoyo8.com.tw/SMSBridge.php?");
					sb.append("MemberID=baokulife");
					sb.append("&Password=").append(MD5.getMD5("baokulife:baokulife1:" + prodId + ":" + msgId));
					sb.append("&MobileNo=").append(phones);
					sb.append("&CharSet=U");
					sb.append("&SMSMessage=").append(content);
					sb.append("&SourceProdID=").append(prodId);
					sb.append("&SourceMsgID=").append(msgId);
				}
				
				returnValue = HttpUtil.getInvoke(sb.toString());
				returnValue = returnValue.replace("\r\n", "");
				logger.info("Return value : " + returnValue);
			} else if (YUNTONGXUN_CHANNEL == smsChannel.intValue()) {
				HashMap<String, Object> result = null;
				CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
				restAPI.init("sandboxapp.cloopen.com", "8883");
				restAPI.setAccount("8a48b5514e5298b9014e704f41781c4d", "6657a44a44b54114984a64196d69d434");
				restAPI.setAppId("aaf98f894e52805a014e704f90f919f2");
				
				if (ytxmap.containsKey(key)) {
					
					String[] datas = new String[objs.length];
					
					for (int i = 0; i < objs.length; i++) {
						message += objs[i];
						datas[i] = objs[i].toString();
						if (i < objs.length - 1) {
							message += "|";
						}
					}
					
					result = restAPI.sendTemplateSMS(phones, ytxmap.get(key) , datas);

					logger.info("SDKTestGetSubAccounts result -> " + result);
			
					if("000000".equals(result.get("statusCode"))){
						@SuppressWarnings("unchecked")
						HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
						Set<String> keySet = data.keySet();
						for(String key:keySet){
							Object object = data.get(key);
							logger.info(key +" = "+object);
						}
						returnValue = "1";
					}else{
						logger.info("错误码 = " + result.get("statusCode") +" 错误信息 = "+result.get("statusMsg"));
						returnValue = "-1";
					}
				} else {
					returnValue = null;
				}
			}

			if (null != returnValue) {
				Connection conn = null;
				PreparedStatement pstm = null;
				
				try {
					conn = JDBCDataSource.getConnection();
					
					conn.setAutoCommit(false);
					
					pstm = conn.prepareStatement("insert into send_record(phone, content, sms_channel, status, is_send, insert_time) values (?, ?, ?, ?, ?, now())");
					pstm.setString(1, phones);
					pstm.setString(2, message);
					pstm.setInt(3, smsChannel);
					
					if ("1".equals(returnValue)) {
						pstm.setInt(4, 7);
						pstm.setBoolean(5, true);
					}else {
						pstm.setInt(4, 8);
						pstm.setBoolean(5, false);
					}
					
					pstm.executeUpdate();
					
					conn.commit();
					conn.setAutoCommit(true);
				} catch (Exception e) {
					try {
						conn.rollback();
					} catch (SQLException e1) {
						logger.error("Rollback fail\n" + e1.getMessage());
					}
					logger.error("Save sms send record fail\n" + e.getMessage());
				} finally {
					try {
						if (pstm != null)
							pstm.close();
						if (conn != null)
							conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	private boolean validSMSDelayInfo(String phone, String content, int channel) {
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		
		if (hour < 7 || hour >= 22){
			Connection conn = null;
			PreparedStatement pstm = null;
			
			try {
				conn = JDBCDataSource.getConnection();
				
				conn.setAutoCommit(false);
				
				pstm = conn.prepareStatement("insert into sms_delay_info(phone, content, channel, send, insert_time) values (?, ?, ?, ?, now())");
				pstm.setString(1, phone);
				pstm.setString(2, content);
				pstm.setInt(3, channel);
				pstm.setBoolean(4, false);

				pstm.executeUpdate();
				
				conn.commit();
				conn.setAutoCommit(true);
				return true;
			} catch (Exception e) {
				try {
					conn.rollback();
				} catch (SQLException e1) {
					logger.error("Rollback fail\n" + e1.getMessage());
				}
				logger.error("Save sms send record fail\n" + e.getMessage());
				return false;
			} finally {
				try {
					if (pstm != null)
						pstm.close();
					if (conn != null)
						conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		
		return false;
	}
}
